﻿#include "LinkedListNode.h"
#include <iostream>

LinkedListNode* reverseLinkedList(LinkedListNode* head)
{
    LinkedListNode* cur = head;
    LinkedListNode* next = nullptr;
    LinkedListNode* prev = nullptr;
    while (cur)
    {
        next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
    }

    return prev;
}

bool isCircleLinkedList(LinkedListNode* head, LinkedListNode** startCircleNode)
{
    auto slow = head;
    auto fast = head;
    bool isCircle = false;
    LinkedListNode* firstMeet = nullptr;
    *startCircleNode = nullptr;
    while (slow && fast)
    {
        if (fast->next)
        {
            fast = fast->next->next;
        }
        else
        {
            fast = nullptr;
        }

        slow = slow->next;

        if (slow && slow == fast)
        {
            firstMeet = slow;
            isCircle = true;
            break;
        }
    }

    if (isCircle)
    {
        slow = head;
        while (true)
        {
            if (slow == firstMeet)
            {
                *startCircleNode = slow;
                break;
            }

            slow = slow->next;
            firstMeet = firstMeet->next;
        }
    }

    return isCircle;
}

int getLinkedListNodeCount(LinkedListNode* head)
{
    if (!head) return 0;

    auto cur = head;
    size_t count = 0;
    while (cur)
    {
        ++count;
        cur = cur->next;
    }

    return count;
}

void delLinkedListNode(LinkedListNode* head)
{
    if (!head) return;

    delLinkedListNode(head->next);
    delete(head);
}

void printLinkedList(LinkedListNode* head)
{
    char msg[1024] = { 0 };
#define TMP_LEN 40
    char tmp[TMP_LEN];
    int index = 0;
    while (head)
    {
        memset(tmp, 0, TMP_LEN);
        sprintf_s(tmp, "%d addr:0x%08x->", head->value, head);
        int len = strlen(tmp);
        memcpy(msg + index, tmp, len);
        index += len;
        head = head->next;
    }

    printf("%s\n", msg);
}